package com.shinbada.modules.sys.web;

import com.shinbada.common.json.AjaxJson;
import com.shinbada.common.utils.StringUtils;
import com.shinbada.core.persistence.Page;
import com.shinbada.core.web.BaseController;
import com.shinbada.excel.ExcelKit;
import com.shinbada.modules.sys.entity.ViewLog;
import com.shinbada.modules.sys.service.ViewLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问日志Controller
 *
 * @author initcap
 * @version 2021-04-21
 */
@RestController
@RequestMapping(value = "/sys/viewLog")
@Api(tags = "访问日志")
public class ViewLogController extends BaseController {

    @Autowired
    private ViewLogService viewLogService;

    @ModelAttribute
    public ViewLog get(@RequestParam(required = false) String id) {
        ViewLog entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = viewLogService.get(id);
        }
        if (entity == null) {
            entity = new ViewLog();
        }
        return entity;
    }

    @RequiresPermissions("user")
    @GetMapping("list")
    @ApiOperation("访问日志列表数据")
    public AjaxJson list(ViewLog viewLog, HttpServletRequest request, HttpServletResponse response) {
        Page<ViewLog> page = viewLogService.findPage(new Page<>(request, response), viewLog);
        return AjaxJson.success().put("page", page);
    }

    @RequiresPermissions("user")
    @GetMapping("queryById")
    @ApiOperation("根据Id获取访问日志数据")
    public AjaxJson queryById(ViewLog viewLog) {
        return AjaxJson.success().put("viewLog", viewLog);
    }

    @RequiresPermissions("user")
    @PostMapping("save")
    @ApiOperation("保存访问日志")
    public AjaxJson save(ViewLog viewLog) {
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(viewLog);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        //新增或编辑表单保存
        viewLogService.save(viewLog);
        return AjaxJson.success("保存访问日志成功");
    }

    @RequiresPermissions("sys:viewLog:del")
    @DeleteMapping("delete")
    @ApiOperation("批量删除访问日志")
    public AjaxJson delete(String ids) {
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            viewLogService.delete(viewLogService.get(id));
        }
        return AjaxJson.success("删除访问日志成功");
    }

    @RequiresPermissions("user")
    @GetMapping(value = "export")
    @ApiOperation("导出日志数据")
    public void exportModel(ViewLog viewLog, HttpServletResponse response) {
        ExcelKit.$Export(ViewLog.class, response).downXlsx(viewLogService.findList(viewLog), false);
    }

}
